<template>
  <div class="exam-form-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>{{ isEditMode ? '编辑考试' : '创建考试' }}</span>
        </div>
      </template>

      <el-form 
        ref="examFormRef" 
        :model="examForm" 
        :rules="formRules" 
        label-width="120px" 
        v-loading="isLoading"
      >
        <el-form-item label="考试标题" prop="title">
          <el-input v-model="examForm.title" placeholder="请输入考试标题" maxlength="100" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="考试描述" prop="description">
          <el-input type="textarea" v-model="examForm.description" placeholder="请输入考试描述" maxlength="500" show-word-limit></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="examForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                value-format="YYYY-MM-DDTHH:mm:ss" 
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="examForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                value-format="YYYY-MM-DDTHH:mm:ss"
                 style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
             <el-form-item label="考试时长" prop="duration">
               <el-input-number v-model="examForm.duration" :min="5" placeholder="分钟"></el-input-number> 分钟
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="及格分" prop="passScore">
              <el-input-number v-model="examForm.passScore" :min="0" placeholder="及格分 (可选)"></el-input-number>
            </el-form-item>
           </el-col>
        </el-row>

        <el-form-item label="组题方式" prop="questionSelectionMode">
            <el-radio-group v-model="examForm.questionSelectionMode">
                <el-radio value="MANUAL">手动选题</el-radio>
                <el-radio value="RANDOM">随机抽题 (待实现)</el-radio> 
            </el-radio-group>
        </el-form-item>

        <el-form-item label="关联班级" prop="classIds">
             <el-select
                v-model="examForm.classIds"
                multiple
                filterable
                placeholder="请选择关联班级"
                style="width: 100%;"
                :loading="loadingClasses"
              >
                <el-option
                  v-for="item in teacherClasses"
                  :key="item.id"
                  :label="item.name + ' (' + item.course + ')'" 
                  :value="item.id"
                />
             </el-select>
        </el-form-item>
        
        <el-form-item label="关联题目" prop="questionIds">
             <div class="question-selector-display">
                <span>已选择 {{ examForm.questionIds.length }} 道题目</span>
                <el-button type="primary" link @click="openQuestionDialog" style="margin-left: 10px;">选择题目</el-button>
             </div>
        </el-form-item>

        <el-divider>考试设置</el-divider>

         <el-form-item label="随机题目顺序" prop="randomQuestions">
            <el-switch v-model="examForm.randomQuestions"></el-switch>
        </el-form-item>
         <el-form-item label="启用防作弊" prop="preventCheating">
            <el-switch v-model="examForm.preventCheating"></el-switch>
             <p class="form-tip">启用后将尝试检测切屏等行为 (具体实现依赖后端)。</p>
        </el-form-item>
         <el-form-item label="结束后显示结果" prop="showResults">
            <el-switch v-model="examForm.showResults"></el-switch>
        </el-form-item>

         <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">{{ isEditMode ? '更新考试' : '立即创建' }}</el-button>
            <el-button @click="handleSaveDraft" :loading="isSavingDraft" v-if="canSaveDraft">保存草稿</el-button>
            <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog 
      v-model="dialogVisible" 
      title="选择考试题目" 
      width="70%" 
      :close-on-click-modal="false"
      @open="onDialogOpen" 
    >
        <el-table
            ref="questionTableRef" 
            :data="dialogTableData"
            v-loading="dialogLoading"
            style="width: 100%"
            max-height="400px"
            @select="handleDialogSelect" 
            @select-all="handleDialogSelectAll"
            row-key="id" 
        >
            <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column> 
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="contentPreview" label="题干预览" min-width="200">
                 <template #default="{ row }">
                    {{ stripHtml(row.content).substring(0, 50) + (stripHtml(row.content).length > 50 ? '...' : '') }}
                </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="100">
                 <template #default="{ row }">
                    {{ getQuestionTypeText(row.type) }}
                </template>
            </el-table-column> 
             <el-table-column prop="difficulty" label="难度" width="80"></el-table-column>
             <el-table-column prop="knowledgePoint" label="知识点" width="150"></el-table-column>
        </el-table>
        <el-pagination
            v-if="dialogPagination.total > 0"
            layout="prev, pager, next, total"
            :total="dialogPagination.total"
            :page-size="dialogPagination.pageSize"
            :current-page="dialogPagination.currentPage"
            @current-change="handleDialogPageChange"
            style="margin-top: 20px; justify-content: flex-end;"
        />
        <template #footer>
            <span class="dialog-footer">
            <el-button @click="cancelQuestionSelection">取消</el-button>
            <el-button type="primary" @click="confirmQuestionSelection">确定</el-button>
            </span>
        </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElDialog, ElTable, ElTableColumn, ElPagination, ElButton, ElSelect, ElOption } from 'element-plus';
import {
  createExam,
  updateExam,
  saveExamDraft,
  getExamDetail
} from '@/services/examService';
import { getTeacherClasses } from '@/services/classService';
import { getQuestionsPage } from '@/services/questionService';

const route = useRoute();
const router = useRouter();

const examFormRef = ref(null);
const isLoading = ref(false);
const isSubmitting = ref(false);
const isSavingDraft = ref(false);

const examId = ref(route.params.id || null);
const isEditMode = computed(() => !!examId.value);

const getInitialExamForm = () => ({
  title: '',
  description: '',
  startTime: null,
  endTime: null,
  duration: 60,
  passScore: null,
  totalScore: null,
  questionSelectionMode: 'MANUAL',
  randomQuestions: false,
  preventCheating: false,
  showResults: true,
  classIds: [],
  questionIds: []
});

const examForm = reactive(getInitialExamForm());

const teacherClasses = ref([]);
const loadingClasses = ref(false);

const dialogVisible = ref(false);
const questionTableRef = ref(null);
const dialogTableData = ref([]);
const dialogPagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
});
const dialogLoading = ref(false);
const selectedQuestionIdSet = ref(new Set());

const stripHtml = (html) => {
  if (!html) return '';
  let doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
}

const getQuestionTypeText = (type) => {
    const map = {
        SINGLE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TRUE_FALSE: '判断',
        FILL_IN_BLANK: '填空',
        SHORT_ANSWER: '简答'
    };
    return map[type] || type;
}

const formRules = reactive({
  title: [{ required: true, message: '请输入考试标题', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [
      { required: true, message: '请选择结束时间', trigger: 'change' },
      { validator: (rule, value, callback) => {
          if (examForm.startTime && value && new Date(value) <= new Date(examForm.startTime)) {
              callback(new Error('结束时间必须晚于开始时间'));
          } else {
              callback();
          }
      }, trigger: 'change'}
  ],
  duration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
  questionSelectionMode: [{ required: true, message: '请选择组题方式', trigger: 'change' }],
});

const resetForm = () => {
  Object.assign(examForm, getInitialExamForm());
  selectedQuestionIdSet.value.clear();
  if (examFormRef.value) {
      examFormRef.value.resetFields(); 
      examForm.duration = 60;
      examForm.passScore = null; 
  }
};

const fetchExamDetails = async () => {
  if (!isEditMode.value) return;
  isLoading.value = true;
  try {
    const response = await getExamDetail(examId.value);
    if (response && response.success && response.data) {
      Object.assign(examForm, response.data);
      selectedQuestionIdSet.value = new Set(response.data.questionIds || []);
    } else {
      ElMessage.error(response.message || '获取考试详情失败');
      router.push('/exams');
    }
  } catch (error) {
    console.error("Error fetching exam details:", error);
    ElMessage.error('加载考试详情时出错');
    router.push('/exams');
  } finally {
    isLoading.value = false;
  }
};

const fetchClassOptions = async () => {
    loadingClasses.value = true;
    try {
        const response = await getTeacherClasses();
        if (response && response.success) {
            teacherClasses.value = response.data || [];
        } else {
            teacherClasses.value = [];
        }
    } catch (error) {
         console.error("Error fetching teacher classes:", error);
         teacherClasses.value = [];
    } finally {
        loadingClasses.value = false;
    }
};

const openQuestionDialog = () => {
    dialogVisible.value = true;
};

const onDialogOpen = () => {
    selectedQuestionIdSet.value = new Set(examForm.questionIds || []);
    fetchDialogQuestions(1);
};

const fetchDialogQuestions = async (page = 1) => {
    dialogLoading.value = true;
    try {
        const params = {
            page: page,
            size: dialogPagination.pageSize,
        };
        const response = await getQuestionsPage(params); 
        if (response && response.success && response.data) {
            dialogTableData.value = response.data.records || [];
            dialogPagination.total = response.data.total || 0;
            dialogPagination.currentPage = page;

            await nextTick();
            if (questionTableRef.value) {
                dialogTableData.value.forEach(row => {
                    if (selectedQuestionIdSet.value.has(row.id)) {
                        questionTableRef.value.toggleRowSelection(row, true);
                    }
                });
            } else {
                console.warn('Question table ref not available for selection sync.');
            }

        } else {
             dialogTableData.value = [];
             dialogPagination.total = 0;
        }
    } catch (error) {
        console.error("Error fetching questions for dialog:", error);
         dialogTableData.value = [];
         dialogPagination.total = 0;
    } finally {
        dialogLoading.value = false;
    }
}

const handleDialogPageChange = (newPage) => {
  fetchDialogQuestions(newPage);
};

const handleDialogSelect = (selection, row) => {
    if (selectedQuestionIdSet.value.has(row.id)) {
        selectedQuestionIdSet.value.delete(row.id);
    } else {
        selectedQuestionIdSet.value.add(row.id);
    }
};

const handleDialogSelectAll = (selection) => {
    const currentPageIds = dialogTableData.value.map(item => item.id);
    if (selection.length > 0) {
        currentPageIds.forEach(id => selectedQuestionIdSet.value.add(id));
    } else {
        currentPageIds.forEach(id => selectedQuestionIdSet.value.delete(id));
    }
};

const confirmQuestionSelection = () => {
    examForm.questionIds = Array.from(selectedQuestionIdSet.value);
    dialogVisible.value = false;
};

const cancelQuestionSelection = () => {
    dialogVisible.value = false;
};

const handleSubmit = async () => {
  if (!examFormRef.value) return;
  await examFormRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true;
      
      // 准备提交的数据
      const payload = { ...examForm }; 
      
      // 确保totalScore有有效值，无论是创建还是编辑模式
      if (!payload.totalScore || payload.totalScore <= 0) {
        // 如果totalScore为空、null、undefined或0，计算所有题目分数总和
        const totalQuestions = payload.questionIds?.length || 0;
        if (totalQuestions > 0) {
          // 假设每题5分，可以根据实际需求调整
          payload.totalScore = totalQuestions * 5;
        } else {
          // 如果没有选择题目，设置默认总分
          payload.totalScore = 100;
        }
      }
      
      // 确保totalScore至少为1（满足后端验证要求）
      if (payload.totalScore < 1) {
        payload.totalScore = 1;
      }
      
      try {
        let response;
        
        if (isEditMode.value) {
          response = await updateExam(examId.value, payload);
        } else {
          response = await createExam(payload);
        }

        if (response && response.success) {
          ElMessage.success(isEditMode.value ? '考试更新成功' : '考试创建成功');
          router.push('/exams');
        } else {
          // 处理API返回的失败响应
          ElMessage.error(response?.message || (isEditMode.value ? '考试更新失败' : '考试创建失败'));
        }
      } catch (error) {
        console.error("Submit exam error:", error);
        // 处理网络错误或其他异常
        if (error.response?.status === 403) {
          ElMessage.error('您没有权限执行此操作，请确认您是该考试的创建者');
        } else if (error.response?.status === 401) {
          ElMessage.error('登录已过期，请重新登录');
        } else {
          ElMessage.error(error.response?.data?.message || (isEditMode.value ? '考试更新失败，请稍后重试' : '考试创建失败，请稍后重试'));
        }
      } finally {
        isSubmitting.value = false;
      }
    }
  });
};

const handleSaveDraft = async () => {
    isSavingDraft.value = true;
    const payload = { ...examForm };
    
    // 确保草稿也有有效的totalScore值
    if (!payload.totalScore || payload.totalScore <= 0) {
      const totalQuestions = payload.questionIds?.length || 0;
      if (totalQuestions > 0) {
        payload.totalScore = totalQuestions * 5;
      } else {
        payload.totalScore = 100; // 草稿默认总分
      }
    }
    
    // 确保totalScore至少为1
    if (payload.totalScore < 1) {
      payload.totalScore = 1;
    }
    
    try {
        let response;
        if (isEditMode.value) {
             response = await saveExamDraft(examId.value, payload);
             if (response && response.success) {
                 ElMessage.success(response.message || '草稿保存成功');
             } 
        } else {
            ElMessage.warning('请先创建考试后才能保存草稿');
            isSavingDraft.value = false;
            return; 
        }
    } catch (error) {
        console.error("Save draft error:", error);
        ElMessage.error('保存草稿失败，请稍后重试');
    } finally {
        isSavingDraft.value = false;
    }
};

const canSaveDraft = computed(() => isEditMode.value);

const goBack = () => {
  router.push('/exams');
};

onMounted(() => {
  fetchClassOptions();
  if (isEditMode.value) {
    fetchExamDetails();
  }
});

watch(() => route.params.id, (newId) => {
  examId.value = newId || null;
  if (!newId) {
    resetForm();
  } else {
    fetchExamDetails();
  }
}, { immediate: false }); 

</script>

<style scoped>
.exam-form-container {
  padding: 20px;
}
.form-tip {
    color: #909399;
    font-size: 12px;
    line-height: 1.5;
    margin-top: 5px;
}
.question-selector-display {
    display: flex;
    align-items: center;
}
</style> 